package angels.client.Helpers;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

public class JSONHelper {
	/*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
     */
    public static String readStreamToString(InputStream is) {
       
        BufferedReader reader = new BufferedReader(new InputStreamReader(is), 1000);
        StringBuilder sb = new StringBuilder();
 
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append('\n');
            }
            
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
    
    public static JSONObject parseJSON(String jsonStr) {
        
        JSONObject object;
        try {
            object = (JSONObject) new JSONTokener(jsonStr).nextValue();
           
            return object;
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }
 
    public static JSONObject parseJSONResponse(HttpResponse response) {
        // Get hold of the response entity
        HttpEntity entity = response.getEntity();
        
        if (entity == null)
            return null;
        
        try {
            InputStream instream = entity.getContent();
            String jsonStr = readStreamToString(instream);
            
            return parseJSON(jsonStr);
        } 
        catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        
    }
}